/*!
 * New Launch.
 * Date: 2015/12/29.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
    'jquery',
    'pageInit',
    'formValidator',
    'formAjax',
    'notification',
    'flowplayer',
    'materialPreview',
    'holder',
    'uploadFiles'
  ], function ($, vamakerPage, formValidator, formAjax, VamOpMsg, Flowplayer, MaterialPreview, holder, UploadFiles) {
    var $dataFrm = $('#data-frm');
  $(function() {
    var $imprMonitorFormCopy = $('.impr-monitor-url-new').detach().removeClass('hidden'),
        $clickMonitorFormCopy = $('.click-monitor-url-new').detach().removeClass('hidden'),
        $showMonitorUrl = $dataFrm.find('input[name="show_monitor_url"]'),
        $clickMonitorUrl = $dataFrm.find('input[name="click_monitor_url"]'),
        validateCallback, newMonitorUrl, delMonitorUrl, sizeValidateCallback, urlValidateCallback,
        $materialSource = $('#material_source').find('input[name="material_source"]'),
        $localMaterial = $('#local_upload_material'),
        $customUrl = $('#custom_material_url'),
        $materialUrl = $('#custom_url'),
        $adspaceWidth = $('#adspace_width'),
        $adspaceHeight = $('#adspace_height'),
        $adspaceLength = $('#adspace_length'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        dataFieldRule, options, dataValidator;
      $materialSource.on('change', function(){
        var $me = $(this),
            meVal = $me.val();
        if (meVal === '1') {
          $customUrl.show();
          $localMaterial.hide();
        } else {
          $customUrl.hide();
          $localMaterial.show();
        }
      });
      $('input[name="material_source"]:checked').trigger('change');

      sizeValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $me.next('#'+errorBox),
        flag = true,
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('Input cannot be empty!');
        } else if (!/^[0-9]*$/.test(meVal)) {
          flag = false;
          msg = VAM.j('Enter can only be integer!');
        } else if(parseInt(meVal,10) < 1) {
          flag = false;
          msg = VAM.j('Enter cannot be less than 1px!');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };
      urlValidateCallback = function (evt) {
        var $me = $(this),
        meVal = $me.val(),
        errorBox = $me.data('err'),
        $errorBox = $('#'+errorBox),
        strRegex = '^((https|http|ftp|rtsp|mms)?://)'
        flag = true,
        re = new RegExp(strRegex),
        msg = '';
        if (meVal === '') {
          flag = false;
          msg = VAM.j('Material url cannot be empty!');
        } else if (!re.test(meVal)){
          flag = false;
          msg = VAM.j('Please input the correct target Url (starting with http:// or https://)');
        };
        if (!flag) {
          msg = '<em class="checky-default-failure">' + msg + '</em>';
          $errorBox.html(msg);
        } else {
          $errorBox.html('');
        };
      };
    $materialUrl.on('blur', urlValidateCallback);
    $adspaceWidth.on('blur', sizeValidateCallback);
    $adspaceHeight.on('blur', sizeValidateCallback);
    $adspaceLength.on('blur', sizeValidateCallback);
    newMonitorUrl = function($monitorFormNew, $monitorFormCopy){
      var len = $monitorFormNew.length;
      if (len < 5) {
        $monitorFormClone = $monitorFormCopy.clone(true);
        $monitorFormNew.last().after($monitorFormClone);
      }
    };
    delMonitorUrl = function(evt){
      evt.preventDefault();
      var $me = $(this),
          opRole = $me.data('type');
      $me.parents('.'+ opRole).remove();
    };
    validateCallback = function(evt){
      var $me = $(this), 
          meVal = $me.val(), matchResult,
          $errBox = $me.next(),
          msg = VAM.j('Please input the correct monitor Url (starting with http:// or https://)');
          matchResult = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(meVal);
      if ($me.data('role') === 'click_url') {
        msg = VAM.j('Please input the correct monitor Url (starting with http:// or https://)');
      }
      if (meVal !== '' && !matchResult) {
        $errBox.html('<em class="checky-default-failure">' + VAM.j('Please input the correct monitor Url (starting with http:// or https://)') + '</em>');
      } else {
        $errBox.html('');
      }
    };
    $dataFrm.on('click', '.add-monitor-url', function(evt){
      evt.preventDefault();
      var $me = $(this),
          opType = $me.data('type');
      if (opType === 'impr-monitor-url') {
        newMonitorUrl($('.' + opType), $imprMonitorFormCopy);
      } else {
        newMonitorUrl($('.' + opType), $clickMonitorFormCopy)
      }
    });
    $dataFrm.on('click', '.del-operate', delMonitorUrl);
    $dataFrm.on('blur', 'input[name="show_monitor_url[]"]', validateCallback);
    $dataFrm.on('blur', 'input[name="click_monitor_url[]"]', validateCallback);
  // New Creative Form.
      dataFieldRule = {
        creative_name:{
          rule:{
              required:{
                  message:VAM.j('Creative cannot be empty')
              }
          },
          messageContainer:'creative_name_err'
        },
        landing_page_main_url:{
          rule:{
              domain:{
                message:VAM.j('Please input the correct domain')
              }
          },
          messageContainer:'landing_page_main_url_err'
        },
        landing_page_url:{
          rule:{
              required:{
                message:VAM.j('Target Url cannot be empty')
              },
              simpleUrl:{
                message:VAM.j('Please input the correct target Url (starting with http:// or https://)')
              }
          },
          messageContainer:'landing_page_url_err'
        }
      };
      options = {
        submitOnSucceed: false,
        onvalidate: function(evt) {
          if (evt.resultList.length <= 0) {
            var $inputErr = $('.monitor-url-error'),
                flag = 0, monitorUrlValidate;
              $materialSource = $('#material_source').find('input[name="material_source"]:checked'),
              materialSourceVal = $materialSource.val(),
              $materialUrl = $('#custom_url'),
              $adspaceWidth = $('#adspace_width'),
              $adspaceHeight = $('#adspace_height');
            $inputErr.each(function(){
              if (!!$(this).html()) {
                flag += 1;
              };
            });
            if (!!flag) {
              return false;
            };
            if (materialSourceVal === '0') {
              var materialVal = $('#upload_material').val(),
                $errorBox = $('#upload_material_err'),
                flag = true,
                msg = '';
              if (materialVal === '') {
                flag = false;
              };
              if (!flag) {
                msg = '<em class="checky-default-failure">' + VAM.j('Upload material cannot be empty') + '</em>';
                $errorBox.html(msg);
                return false;
              } else {
                $errorBox.html('');
              };
            } else {
              $materialUrl.trigger('blur', urlValidateCallback);
              $adspaceWidth.trigger('blur', sizeValidateCallback);
              $adspaceHeight.trigger('blur', sizeValidateCallback);
              var materialUrlErr = $('#custom_url_err').html(),
                  adspaceWidthErr = $('#width_err').html(),
                  adspaceHeightErr = $('#height_err').html();
              if (materialUrlErr !== '' || adspaceWidthErr !== '' || adspaceHeightErr !== '') {
                return false;
              };
            };
            $dataFrm.ajaxSubmit({
                beforeSubmit: function() {
                  $submitBtn.button('loading');
                },
                success: function (data) {
                  $submitBtn.button('reset');
                if (data.status === 'success') {
                  VamOpMsg.messager(data);
                  if (VAM.getVar('CLOSE_DIALOG_FLAG') === true) {
                    $('.creative-preview-modal', window.parent.document).find('.btn-default').trigger('click');
                  } else {
                    window.location.href = 'creative-list';
                  }
                } else {
                  VamOpMsg.messager(data);
                }
                }
            });
          };
        }
      };
      formValidator.validate($dataFrm, dataFieldRule, options);
      dataValidator = formValidator.dataValidator;
      dataValidator.addRule('effectiveNumber',function(val, opt){
        return !!(val && /^\d+(\.\d{1,2})?$/.test(val));
      });
      dataValidator.addRule('domain',function(val, opt){
        return !!(val && /^([a-z0-9]+[a-z0-9\-]*\.){1,2}([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)$/.test(val));
      });
  });
  // Init Creative Upload.
  $(function () {
    var $uploadMaterial = $('#upload-material'),
      $uploadMaterialModal = $('#upload-material-modal'),
      $uploadMaterialInput = $('#upload_material'),
      $uploadMaterialOperate = $('#upload-confirm-operate'),
      $creativeMaterialDefault = $('#creative_material_default'),
      videoPluginUrl = VAM.getVar('VIDEO_PLUGIN_URL');
    Flowplayer.conf = {
      swf: videoPluginUrl,
      muted: true,
      preload: 'metadata',
      tooltip: false,
      volume: 0.3
    };
    $uploadMaterialModal.on('hidden.bs.modal', function (evt) {
      var $me = $(this);
      $('#progress .progress-bar').css('width','0%').text('0%');
      $('#files').find('tbody').html('');
    });

    $uploadMaterial.on('click', function (evt) {
      var $me = $(this);
      $uploadMaterialModal.modal('show');
    });
    
    $uploadMaterialOperate.on('click', function(evt) {
      var $me = $(this),
        $uploadMaterialErr = $('#upload_material_err');
        materialId = $me.data('materialId'),
        prevewInfo = $me.data('materialInfo');
      evt.preventDefault();
      // console.log(materialId);
      // console.log(prevewInfo);
      if (materialId !== '') {
        $uploadMaterialInput.val(materialId);
        $uploadMaterialModal.modal('hide');
        $uploadMaterialErr.html('');
        // TODO: creative material preview.
        MaterialPreview.previewSingle($('.creative-preview-wrap'), prevewInfo, materialId);
        $('.creative-preview-wrap').find('.flowplayer').flowplayer();
        $('#creative-preview-details').children().remove();
      } else {
        $uploadMaterialInput.val('');
      };
    });
  });
  // Upload Creative Material.
  $(function () {
      'use strict';
      var url = VAM.getVar('UPLOAD_MATERIAL_URL'),
          $fileUpload = $('#fileupload'),
          $progressBar = $('#progress .progress-bar'),
          $table = $('#files').find('table tbody');
      $fileUpload.fileupload({
          url: url,
          dataType: 'json',
          done: function (e, data) {
            if (data.result.status === 'success') {
              var materialData = data.result.data,
               list = materialData['table'],
               listStr = '';
              // console.log(materialData);
              VamOpMsg.messager(data.result);
              listStr = '<tr>'
                      + '<td>' + materialData.id + '</td>'
                      + '<td>' + list.name + '</td>'
                      + '<td>' + list.size + '</td>'
                      + '<td>' + list.date + '</td>'
                      + '<td>' + list.judgeInfo + '</td>'
                      + '<td>' + list.updater + '</td>'
                      + '</tr>';
              $table.append(listStr);
              $('#upload-confirm-operate').data('materialId', materialData.id).data('materialInfo', materialData['preview']);
            }else {
              VamOpMsg.messager(data.result);
              $('#upload-confirm-operate').data('materialId', '');
            };
          },
          progressall: function (e, data) {
              var progress = parseInt(data.loaded / data.total * 100, 10);
              $progressBar.css('width','0%').text('0%');
              $progressBar.css(
                  'width',
                  progress + '%'
              ).text(progress + '%');
          }
      })
      .prop('disabled', !$.support.fileInput)
      .parent().addClass($.support.fileInput ? undefined : 'disabled');
  });
  //Creative Vocation.
  $(function(){
    var creativeVocation = $.parseJSON(VAM.getVar('CREATIVE_VOCATION')),
      $vocationLarge = $('#creative_vocation_large'),
      $vocationSmall = $('#creative_vocation_small');
    for(var key in creativeVocation){
      if(creativeVocation.hasOwnProperty(key)) {
        $vocationLarge.append('<option value="'+key+'">' + key + '</option>');
      }
    }

    $vocationLarge.on('change',function(){
      var $me = $(this),
        vocationSmall = creativeVocation[$me.val()],
        i,j;
      $vocationSmall.children().remove();
      $vocationSmall.append('<option value="' + VAM.j('All') + '">' + VAM.j('All') + '</option>');
      for (i=0, j=vocationSmall.length; i<j; i++) {
        $vocationSmall.append('<option value="' + vocationSmall[i] + '">' + vocationSmall[i] +'</option>');
      }
    });

    var creativeParentVocation = VAM.getVar('parent_category');
    var creativeChildVocation = VAM.getVar('child_category');

    $("#creative_vocation_large option[value='"+creativeParentVocation+"']").attr('selected', "selected");
    $vocationLarge.trigger('change');
    $("#creative_vocation_small option[value='"+creativeChildVocation+"']").attr('selected', "selected");
  });
  // Video Creative Preview.
  $(function() {
    var videoPluginUrl = VAM.getVar('VIDEO_PLUGIN_URL'),
      $creativePreviewWrap = $('#creative-preview-details'),
      width = $('.creative-width').val(),
      height = $('.creative-height').val(),   
      type = $('.creative-type').val(),
      url = $('.creative-url').val(),
      info = {}, materialId = '';
    Flowplayer.conf = {
      swf: videoPluginUrl,
      engine: 'flash',
      muted: true,
      preload: 'auto',
      tooltip: false,
      volume: 0.3
    };
    info = {
      'width': width,
      'height': height,
      'type': type,
      'address': url
    };
    // console.log(info);
    MaterialPreview.previewSingle($creativePreviewWrap, info, materialId);
    $creativePreviewWrap.find('.flowplayer').flowplayer();
  });
});
